<?php
/**
 * Created by PhpStorm.
 * User: fzf
 * Date: 19-4-25
 * Time: 下午5:09
 */
namespace app\common\wechat;

use app\common\model\WechatAutoreply;
use app\common\model\Wx;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Factory;
use app\common\model\WechatResponse;
use EasyWeChat\Kernel\Messages\MiniProgramPage;

class Wechat
{
    protected $app;

    protected $methods=[
        'getText',
        'getImage',
        'getVoice',
        'getVideo',
        'getLocation',
        'getLink',
        'getFile',
        'onClick',
        'onView',
        'onsubscribe',
        'onUnsubscribe',
        'onLocation'

    ];

    function getRes($eventkey){

        $ret=WechatResponse::get(['eventkey'=>$eventkey,'status'=>'normal']);
        if($ret){
            $ret->content= json_decode($ret->content,true);
            return $ret;
        }

        return false;
    }

    //执行资源里定义的工作
    function queryRes($eventkey,$message){
        $res=$this->getRes($eventkey);
        //print_r($message);
        if($res){
            if($res['type']=='text'){
                //自动回复
                return $res['content']['content'];
            }else{

                $service=$this->app->customer_service;
                //$msg='<a  href="http://www.qq.com"  data-miniprogram-appid="wx57b669f10b6cf56c"  data-miniprogram-path="pages/index/index">  点击跳小程序</a>';

                $msg=new MiniProgramPage(['thumb_media_id'=>'', 'appid'=>'wx57b669f10b6cf56c', 'pagepath'=>'pages/index/index',]);
                $service->message($msg)->to($message['FromUserName'])->send();

                return '1';
            }

        }
    }

    function  __construct()
    {

        $config=config('wechat');
        $this->app= Factory::officialAccount($config);


    }


    function handle(){
        try{
            $this->app->server->push(function($message){

                $type=strtolower($message['MsgType']);
                if($type=='event'){
                    $event=strtolower($message['Event']);
                    $method="on{$event}";
                }else{
                    $method="get{$type}";
                }
                return call_user_func_array([$this,$method],['message'=>$message]);

            });
            $response = $this->app->server->serve();
            return $response->send();
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

    //菜单点击事件消息
    function onclick($message){
        $eventKey=empty($message['EventKey'])?null:strtolower($message['EventKey']);
        $res=null;
        if($eventKey){
            return $this->queryRes($eventKey,$message);
        }
        return '未知菜单';
    }

    function getText($message){
//        $content=$message['Content'];
//        //自动回复
//        $autoreply=WechatAutoreply::get(['text'=>$content, 'status' => 'normal']);
//        if($autoreply){
//            return $this->queryRes($autoreply->eventkey,$message);
//        }

        return '找我什么事啊';
    }


    //订阅
    function onsubscribe($message){


        $ret=$this->app->user->get($message['FromUserName']);
        if($ret){
            $user=Wx::where('openid',$message['FromUserName'])->find();
            if($user){
                $user->subscribe=1;
                $user->save();
            }else{

                $data=[
                    'avatarurl'=>$ret['headimgurl'],
                    'openid'=>$ret['openid'],
                    'nickname'=>$ret['nickname'],
                    'country'=>$ret['country'],
                    'province'=>$ret['province'],
                    'city'=>$ret['city']
                ];
                $ret['avatarurl']=$ret['headimgurl'];
                $ret['status']=1;
                Wx::create($data);
            }

            return '你好'.$ret['nickname'].'!';
        }

        return '出错了';

    }

    function onUnsubscribe($message){
        $user=Wx::where('openid',$message['FromUserName'])->find();
        $user->subscribe=0;
        $user->save();
        return 'success';

    }

    function getVoice($message){

       // print_r($message);
        /*

          Array
        (
            [ToUserName] => gh_e5ceeaf8dbac
            [FromUserName] => o-JsU5sGpGF3-Tbi-MrEpWgraac8
            [CreateTime] => 1564043333
            [MsgType] => voice
            [MediaId] => uYbS81vXQ0ahWtlznIc63QhinuSDymhFkAkr1TkjVYcL_6T8mZedmDIZ4jY8xtMb
            [Format] => amr
            [MsgId] => 6717514964761837568
            [Recognition] => 好的，我们见了面再说。
        )
         */
        return 'success';
    }


    function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        return '未知的信息类型';
    }

}
